package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.StrategyCatalog;
import cn.wolfcode.trip.base.domain.StrategyContent;
import cn.wolfcode.trip.base.domain.StrategyDetail;
import cn.wolfcode.trip.base.mapper.StrategyCatalogMapper;
import cn.wolfcode.trip.base.mapper.StrategyContentMapper;
import cn.wolfcode.trip.base.mapper.StrategyDetailMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IStrategyDetailService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class StrategyDetailServiceImpl implements IStrategyDetailService{
    @Autowired
    private StrategyDetailMapper strategyDetailMapper;
    @Autowired
    private StrategyCatalogMapper strategyCatalogMapper;
    @Autowired
    private StrategyContentMapper strategyContentMapper;


    @Override
    public PageInfo selectForList(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<StrategyDetail> list = strategyDetailMapper.selectForList(qo);
        return new PageInfo(list);
    }

    @Override
    public void saveOrUpdate(StrategyDetail strategyDetail) {
        //设置发布时间
        if(strategyDetail.getState() == StrategyDetail.STATE_RELEASE){
            strategyDetail.setReleaseTime(new Date());
        }

        //序号自增
        if(strategyDetail.getSequence()==null){
            int seq = strategyDetailMapper.selectAutoSequence(strategyDetail.getCatalog().getId());
            strategyDetail.setSequence(seq + 1);
        }

        StrategyContent strategyContent = strategyDetail.getStrategyContent();
        if(strategyDetail.getId() != null){
            strategyDetailMapper.updateByPrimaryKey(strategyDetail);

            strategyContent.setId(strategyDetail.getId());
            strategyContentMapper.updateByPrimaryKey(strategyContent);
        }else{
            strategyDetail.setCreateTime(new Date());
            strategyDetailMapper.insert(strategyDetail);

            strategyContent.setId(strategyDetail.getId());
            strategyContentMapper.insert(strategyContent);
        }
    }

    @Override
    public List<StrategyCatalog> getCatalogBystrategyId(Long strategyId) {
        return strategyCatalogMapper.selectCatalogBystrategyId(strategyId);
    }

    @Override
    public StrategyContent getContentByStrategyId(Long detailId) {
        return strategyContentMapper.selectByPrimaryKey(detailId);
    }

    @Override
    public StrategyDetail get(Long id) {
        return strategyDetailMapper.selectByPrimaryKey(id);
    }


}
